<?php

class TagsController extends Controller
{
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules()
	{
		return array(
			array('deny',
				'users'=>array('?'),
			),
		);
	}

	public function actionCreate()
	{
		$model=new Tags;

        $this->performAjaxValidation($model);

		if(isset($_POST['Tags']))
		{
			$model->attributes=$_POST['Tags'];
			if($model->save())
				BlogTool::successRedirect('成功添加标签', 'tags/index');
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionUpdate($id)
	{
		$model = $this->loadModel($id, self::$UPDATE);

        $this->performAjaxValidation($model);

		if(isset($_POST['Tags']))
		{
			$model->attributes = $_POST['Tags'];
			if($model->save())
				BlogTool::successRedirect('修改标签成功', 'tags/index');
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionDelete($id)
	{
        $this->loadModel($id, self::$DELETE)->delete();
        BlogTool::successRedirect('删除标签成功', 'tags/index');
	}

	public function actionIndex()
	{
        $model = new Tags();

        $criteria = new CDbCriteria();
        $criteria->select = 'id, tag_name, tag_count';
        $criteria->order = 'id desc';

        // 如果有搜索关键词...
        if($_GET['act'] == 'search')
            $criteria->addSearchCondition('tag_name', $_GET['tag_name']);

        $pager = parent::showPager($model, $criteria, 1);

        $data = $model->findAll($criteria);

		$this->render('index',array(
			'data'=>$data,
            'pager'=>$pager
		));
	}

	public function actionAdmin()
	{
		$model=new Tags('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Tags']))
			$model->attributes=$_GET['Tags'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	public function loadModel($id, $sec)
	{
		$tag = new Tags($sec);
        $model = $tag->findByPk((int)$id);

		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='tags-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
